package servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.DB_Connection;

import java.sql.*;

/**
 * Servlet implementation class LogIn
 */
public class Servlet_LogIn extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servlet_LogIn() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		boolean pass = false;
		
		try {
			
			Connection conn = DB_Connection.getConnection();
			
			
			Statement st = conn.createStatement();
			ResultSet result = st.executeQuery("SELECT * FROM users");
			
			
			while(result.next()){
				String usrn = result.getString("name").trim();
				if(usrn.equals(username.trim())){

					if(password.equals(result.getString("pass"))){
						pass = true;
					}
				}
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		if(pass){
			RequestDispatcher dispatcher = request.getRequestDispatcher("MainView.jsp");
			dispatcher.forward(request, response);
		} else {
			request.setAttribute("error", "failed to login");
			RequestDispatcher dispatcher = request.getRequestDispatcher("LogInView.jsp");
			dispatcher.forward(request, response);
		}
	}

}
